import { createRouter, createWebHistory } from 'vue-router'

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/trace'
  },
  // 登录与注册路由
  {
    path: '/login',
    name: 'LoginView',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'RegisterView',
    component: () => import('../views/RegisterView.vue')
  },
  // 溯源查询路由
  {
    path: '/trace',
    name: 'TraceQueryView',
    component: () => import('../views/trace/TraceQueryView.vue')
  },
  {
    path: '/product/:id',
    name: 'ProductDetailView',
    component: () => import('../views/trace/ProductDetailView.vue')
  },
  // 管理员路由
  {
    path: '/admin',
    name: 'AdminHomeView',
    component: () => import('../views/admin/AdminHome.vue'),
    redirect: '/admin/dashboard',
    meta: { requiresAuth: true, role: 'ADMIN' },
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboardView',
        component: () => import('../views/admin/Dashboard.vue'),
        meta: { title: '控制台' }
      },
      {
        path: 'user-management',
        name: 'UserManagementView',
        component: () => import('../views/admin/UserManagement.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'role-management',
        name: 'RoleManagementView',
        component: () => import('../views/admin/RoleManagement.vue'),
        meta: { title: '角色管理' }
      },
      {
        path: 'menu-management',
        name: 'MenuManagementView',
        component: () => import('../views/admin/MenuManagement.vue'),
        meta: { title: '菜单管理' }
      },
      {
        path: 'dictionary-management',
        name: 'dictionary-management',
        component: () => import('../views/admin/DictionaryManagement.vue'),
        meta: {
          title: '字典管理'
        }
      },
      {
        path: 'log',
        name: 'system-log',
        component: () => import('../views/admin/SystemLog.vue'),
        meta: {
          title: '系统日志'
        }
      },
      {
        path: 'trace-stats',
        name: 'trace-stats',
        component: () => import('../views/admin/TraceStats.vue'),
        meta: {
          title: '溯源统计'
        }
      },
      {
        path: 'farming-management',
        name: 'farming-management',
        component: () => import('../views/admin/FarmingManagement.vue'),
        meta: {
          title: '种植信息管理'
        }
      },
      {
        path: 'profile',
        name: 'admin-profile',
        component: () => import('../views/admin/UserProfile.vue'),
        meta: {
          title: '个人设置'
        }
      }
    ]
  },
  // 种植户路由
  {
    path: '/farmer',
    name: 'FarmerHomeView',
    component: () => import('../views/farmer/FarmerHome.vue'),
    redirect: '/farmer/dashboard',
    meta: { requiresAuth: true, role: 'FARMER' },
    children: [
      {
        path: 'dashboard',
        name: 'FarmerDashboardView',
        component: () => import('../views/farmer/FarmerDashboardView.vue'),
        meta: { title: '控制台' }
      },
      {
        path: 'info-entry',
        name: 'InfoEntryView',
        component: () => import('../views/farmer/InfoEntry.vue'),
        meta: { title: '信息录入' }
      },
      {
        path: 'qrcode',
        name: 'QRCodeManagementView',
        component: () => import('../views/farmer/QRCodeManagement.vue'),
        meta: { title: '溯源码管理' }
      },
      {
        path: 'order',
        name: 'FarmerOrderView',
        component: () => import('../views/farmer/OrderManagement.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: 'stats',
        name: 'FarmerStatsView',
        component: () => import('../views/farmer/FarmerStats.vue'),
        meta: { title: '种植统计' }
      },
      {
        path: 'profile',
        name: 'FarmerProfileView',
        component: () => import('../views/farmer/FarmerProfileView.vue'),
        meta: { title: '个人设置' }
      }
    ]
  },
  // 经销商路由
  {
    path: '/dealer',
    name: 'DealerHomeView',
    component: () => import('../views/dealer/DealerHome.vue'),
    redirect: '/dealer/dashboard',
    meta: { requiresAuth: true, role: 'DEALER' },
    children: [
      {
        path: 'dashboard',
        name: 'DealerDashboardView',
        component: () => import('../views/dealer/DealerDashboardView.vue'),
        meta: { title: '控制台' }
      },
      {
        path: 'order-management',
        name: 'OrderManagementView',
        component: () => import('../views/dealer/OrderManagement.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: 'order-management/create',
        name: 'CreateOrderView',
        component: () => import('../views/dealer/OrderManagement.vue'),
        meta: { title: '创建订单', isCreate: true }
      },
      {
        path: 'logistics-management',
        name: 'LogisticsManagementView',
        component: () => import('../views/dealer/LogisticsManagement.vue'),
        meta: { title: '物流管理' }
      },
      {
        path: 'customer-management',
        name: 'CustomerManagementView',
        component: () => import('../views/dealer/CustomerManagementView.vue'),
        meta: { title: '客户管理' }
      },

      {
        path: 'profile',
        name: 'DealerProfileView',
        component: () => import('../views/dealer/DealerProfileView.vue'),
        meta: { title: '个人设置' }
      }
    ]
  },
  // 404路由
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/trace/TraceQueryView.vue'),
    meta: { title: '页面未找到' },
    beforeEnter: (to, from, next) => {
      console.log('404路由被触发，路径:', to.path)

      // 检查是否是菜单路径但未正确配置
      const menuPaths = [
        '/admin/', '/farmer/', '/dealer/',
        '/profile', '/user-management', '/role-management',
        '/menu-management', '/dictionary-management'
      ]

      // 如果是以上路径前缀，先输出日志
      if (menuPaths.some(path => to.path.startsWith(path))) {
        console.warn('导航到未配置的菜单路径:', to.path)
      }

      // 否则正常重定向到溯源页面
      next()
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('路由守卫: 从', from.path, '导航到', to.path)

  // 判断路由是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    console.log('目标路由需要登录权限')
    // 从本地获取用户信息，实际项目应该使用Vuex管理
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isLogin = userInfo.token

    if (!isLogin) {
      console.log('用户未登录，重定向到登录页')
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将当前路由信息传递给登录页，以便登录成功后跳回
      })
    } else {
      // 判断用户角色是否有权限访问
      const role = userInfo.role
      console.log('用户已登录，角色为:', role)

      // 检查路由是否需要特定角色
      const requireRole = to.matched.some(record => record.meta.role && record.meta.role !== role)

      if (requireRole) {
        // 无权限访问，跳转到对应角色的首页
        const rolePath = `/${role.toLowerCase()}/dashboard`
        console.log(`用户角色 ${role} 无权访问 ${to.path}，重定向到 ${rolePath}`)
        next({ path: rolePath })
      } else {
        console.log('用户有权访问此路由')
        // 有权限，正常访问
        next()
      }
    }
  } else {
    console.log('目标路由不需要登录权限，直接访问')
    // 不需要登录权限，直接访问
    next()
  }
})

// 添加路由完成后的回调，用于调试
router.afterEach((to, from) => {
  console.log('路由导航完成: 从', from.path, '到', to.path)
})

export default router
